package com.dbapp.shopping.controller;

import com.dbapp.shopping.domain.User;
import com.dbapp.shopping.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.security.Principal;

@Controller
public class RechargeController {

    private Service service;

    @Autowired
    public RechargeController(Service service) {
        this.service = service;
    }

    @GetMapping("/recharge")
    public String rechargePage(Model model, Principal principal) {
        Authentication authentication = (Authentication) principal;
        if (principal != null && authentication.isAuthenticated()) {
            model.addAttribute("status", true);
            model.addAttribute("user", (User) authentication.getPrincipal());
        } else {
            model.addAttribute("status", false);
            return "redirect:/";
        }
        model.addAttribute("checkrecharge", true);
        return "recharge";
    }

    @PostMapping("/recharge")
    public String processRecharge(Model model, String recharge, @AuthenticationPrincipal User user)
    {
        model.addAttribute("user", user)
                .addAttribute("get", false)
                .addAttribute("status", true)
                .addAttribute("checkrecharge", true);
        if(recharge.isEmpty() || !service.isPrice(recharge))
        {
            model.addAttribute("checkrecharge", false);
            return "/recharge";
        }
        user.setBalance(user.getBalance() + Double.valueOf(recharge));
        user = service.saveUser(user);
        model.addAttribute("user", user);
        return "redirect:/profile=" + user.getUsername();
    }

}